package com.heima.article.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.IArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.wemedia.dtos.WmNewsDto;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.RequiredArgsConstructor;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class Listener {
    private final IArticleService articleService;
    private final ApArticleConfigService apArticleConfigService;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @KafkaListener(topics = "wmNewsDownOrUp-topic")
    public void onMessageWmNewsDownOrUp(ConsumerRecord<String, String> record, Consumer<String, String> consumer) {
        if (!StringUtils.isEmpty(record)) {
            String value = record.value();
            WmNewsDto wmNewsDto = JSONObject.parseObject(value, WmNewsDto.class);
            //1.查询文章信息
            //2.修改文章配置
            LambdaUpdateWrapper<ApArticleConfig> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticleConfig::getArticleId, wmNewsDto.getArticleId())
                    .set(ApArticleConfig::getIsDown, wmNewsDto.getEnable());
            apArticleConfigService.update(updateWrapper);

            System.err.println(record.value());
            System.err.println(record.offset());
            //提交偏移量
            consumer.commitSync();
        }
    }

    @KafkaListener(topics = "apArticleGenerate-topic")
    public void onMessageApArticleGenerate(ConsumerRecord<String, String> record, Consumer<String, String> consumer) throws IOException, TemplateException {
        //1.获取文章内容
        String articleIdStr = record.value();
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, Long.parseLong(articleIdStr)));
        if (apArticleContent != null && org.apache.commons.lang3.StringUtils.isNotBlank(apArticleContent.getContent())) {
            //2.文章内容通过freemarker生成html文件
            StringWriter out = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");

            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(apArticleContent.getContent()));

            template.process(params, out);
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            //3.把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            //4.修改ap_article表，保存static_url字段
            ApArticle article = new ApArticle();
            article.setId(apArticleContent.getArticleId());
            article.setStaticUrl(path);
            articleService.updateById(article);
        }


        System.err.println(record.value());
        System.err.println(record.offset());
        //提交偏移量
        consumer.commitSync();
    }
}
